import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/values/index.dart';

import 'index.dart';

///提供netBuilder
class CoreNetBuilder extends CommonNetBuilder {
  static Future<Map<String, dynamic>> get params async {
    return {
      'version': await ConstantValues.version,
      'thjenc': ConstantValues.client,
      'devjte': await ConstantValues.device,
      'jdfw': ConstantValues.idfa,
      'devjte_copen': ConstantValues().deviceToken,
      'cdjd': await ConstantValues.tdid,
      'hng': await LocationService.instance.longitude, //经度
      'hwc': await LocationService.instance.latitude, //纬度
      'appname': await ConstantValues.appName,
    };
  }

  @override
  String getBaseUrl() => "http://lamapi.chwxkj.top/";

  @override
  Future<Map<String, dynamic>> initCommonParams() async => params;

  @override
  Future<Map<String, dynamic>> initHeaders() async => Future.value({});

  ///throw Exception(); 可以让下一步的[showError]不进行弹窗提示
  @override
  Future reduceJson(dynamic json) async {
    if (json is Map) {
      int code = json['code'] ?? 0;

      if (code == 200 || code == 0) {
        ///请求成功
        return json;
      } else if (code == 401) {
        ///需要登录
        // CommonDialog.showLoginDialog();
        // Loading.dismiss();
        // throw Exception();
      } else {
        Loading.toast(json['msg']);
        return json;
      }
    } else {
      return json;
    }
  }

  @override
  void showError(CommonNetError errorType, Exception error) {
    switch (errorType) {
      case CommonNetError.netError:
        Loading.toast('请检查网络连接');
        return;
      case CommonNetError.connectTimeout:
        Loading.toast('连接超时，请检测网络');
        return;
      case CommonNetError.sendTimeout:
        Loading.toast('发送超时，请检测网络');
        return;
      case CommonNetError.receiveTimeout:
        Loading.toast('接收超时，请检测网络');
        return;
      case CommonNetError.response:
        Loading.toast(error.toString());
        return;
      case CommonNetError.formatError:
        Loading.toast('数据解析失败');
        return;
      case CommonNetError.cancel:
        Loading.toast('请求已关闭');
        return;
      case CommonNetError.other:
      default:
        if (error.toString() == 'Exception') return;
        Loading.toast(error.toString());
        return;
    }
  }

  @override
  void print(msg) {
    Log.log('----- net error ----- :$msg');
  }
}
